#-*-coding:utf-8-*-
# Create your views here.
from models import Salesperson,Role
from models import Salesperson_groups  #import modles  Salesperson_groups  huangzy edit
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import forms
from django.core.paginator import Paginator, InvalidPage



"""调用添加用户显示页"""
def addsales (request):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    salesgroup = Salesperson_groups.objects.order_by('id')   #sales group  huangzy edit
    salesgroup = Salesperson_groups.objects.filter(status=1)   #sales group  huangzy edit
    roles = Role.objects.order_by('id')  #sales group  huangzy edit
    roles = Role.objects.filter(status=1)
    return render_to_response('adminaddsales.html',{'salesgroup':salesgroup,'roles':roles})  #sales group  huangzy edit

"""保存用户信息"""
def savesales (request):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    if request.method == 'POST':
            new_data = request.POST.copy()
            sendsmsv=request.POST.get('sendsms','0')
            sendsmsv=int(sendsmsv)
            if new_data.has_key('id'):
                sales=Salesperson.objects.get(pk=new_data['id'])
                sales.name=new_data['name']
                sales.truename=new_data['truename']
                sales.tel=new_data['tel']
                sales.mobile=new_data['mobile']
                sales.email=new_data['email']
                sales.level=new_data['level']
                sales.group = new_data['group']
                sales.sendsms=sendsmsv
            else:
                sales2=Salesperson.objects.filter(name=new_data['name'])
                errormsg=''
                if sales2:
                    errormsg='The sales have existed'
                    return render_to_response('adminaddsales.html',{'errormsg': errormsg})
                sales=Salesperson(
                name=new_data['name'],
                password=new_data['password'],
                truename=new_data['truename'],
                tel=new_data['tel'],
                mobile=new_data['mobile'],
                email=new_data['email'],
                level=new_data['level'],
                group = new_data['group'],
                sendsms=sendsmsv,
                )
            sales.save()
    return HttpResponseRedirect('/slist/')

"""调用修改用户密码---管理员方有的权限"""
def modifypwd (request,s_id):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    sales = get_object_or_404(Salesperson, pk=s_id)
    return render_to_response('modifypwd.html',{'sales': sales})

"""保存修改后的密码"""
def savenewpwd (request):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    new_data = request.POST.copy()
    try:
        sales=Salesperson.objects.get(name=new_data['name'])
        sales.password=new_data['password']
        sales.save()
        return HttpResponseRedirect('/slist/')
    except Salesperson.DoesNotExist:
        flashmsg="Sorry ,No such sales"
        return render_to_response('flash.html',{'flashmsg': flashmsg})

"""SALES用户主列表"""
def slist(request,page='1'):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    salesperson = Salesperson.objects.order_by('-id')
    salesgroups = Salesperson_groups.objects.order_by('id')   #add reg area huangzy edit

    paginator=Paginator(salesperson,10)
    try:
        page=int(page)
#        page = int(request.GET.get('page','1'))
        salesperson = paginator.page(page)
    except:
        return HttpResponseRedirect('/slist',{'level':request.session['level']})
    return render_to_response('slist.html',{
    'paginator':paginator,
    'salesperson':salesperson.object_list,
    'salesgroups':salesgroups,
    'is_paginated': paginator.num_pages > 1,
    'has_next': salesperson.has_next(),
    'has_previous': salesperson.has_previous(),
    'current_page': page,
    'next_page': page + 1,
    'previous_page': page - 1,
    'pages': paginator.num_pages,
    'page_numbers': range(paginator.num_pages+1)[1:],
    'hits' : paginator.count,
    'level':request.session['level'],
    })

"""调用修改显示页"""
def edit_s(request, s_id):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    salesperson = get_object_or_404(Salesperson, pk=s_id)
    salesgroup = Salesperson_groups.objects.order_by('id')  #sales group  huangzy edit
    salesgroup = Salesperson_groups.objects.filter(status=1)   #sales group  huangzy edit
    roles = Role.objects.order_by('id')  #sales group  huangzy edit
    roles = Role.objects.filter(status=1)
    return render_to_response('adminaddsales.html',{'salesperson': salesperson,'salesgroup':salesgroup,'roles':roles})   #sales group  huangzy edit


"""删除用户操作显示页"""
def del_s (request,s_id=""):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    #Salesperson.objects.filter(pk=s_id).delete()
    #return HttpResponseRedirect('/crm/slist/')
    salesperson = get_object_or_404(Salesperson, pk=s_id)
    return render_to_response('del_s_ask.html',{'salesperson': salesperson})

"""删除用户执行"""
def del_s2 (request,s_id=""):
    """管理员才有权限"""
    #if request.session['level']!="administrators":
        #return HttpResponseRedirect('/')
    Salesperson.objects.filter(pk=s_id).delete()
    return HttpResponseRedirect('/slist/')

"""修改名字"""
def modifyname (request):
    """管理员or sales才有权限"""
    if request.session['id']=="":
        return HttpResponseRedirect('/')
    salesperson = get_object_or_404(Salesperson, pk=request.session['id'])
    return render_to_response('modifyname.html',{'salesperson': salesperson,'level':request.session['level']})
	

"""保存修改后的信息"""
def savename (request):
    """登陆才有权限"""
    if request.session['id']=="":
        return HttpResponseRedirect('/')
    post_data = request.POST.copy()
    salesperson = get_object_or_404(Salesperson, pk=request.session['id'])
    if request.session['level'] == 'administrators':        
        if post_data['name'] !=salesperson.name:
            sales=Salesperson.objects.filter(name=post_data['name'])
            if sales:            
                flashmsg="This name have exist,please choose another! "
                return render_to_response('modifyname.html',{'flashmsg': flashmsg,'salesperson': salesperson,'level':request.session['level']})
            else:
                salesperson.name=post_data['name']
    salesperson.truename=post_data['truename']
    salesperson.tel=post_data['tel']
    salesperson.mobile=post_data['mobile']
    salesperson.email=post_data['email']
    salesperson.save()
    return HttpResponseRedirect('/modifyname/')
    

"""修改密码"""
def savepassword (request):
    """管理员才有权限"""
    if request.session['id']=="":
        return HttpResponseRedirect('/')
    post_data = request.POST.copy()
    oldpassword=post_data['oldpassword']
    password=post_data['password']
    sid=request.session['id']
    myinfo=Salesperson.objects.get(pk=sid)
    salesperson = get_object_or_404(Salesperson, pk=request.session['id'])
    if oldpassword!=myinfo.password :
        flashmsg="Your old password is not true! "
        return render_to_response('modifyname.html',{'flashmsg2': flashmsg,'salesperson': salesperson,'level':request.session['level']})
    else:
        myinfo.password=password
        myinfo.save()
        flashmsg="Success! "
        return render_to_response('modifyname.html',{'flashmsg2': flashmsg,'salesperson': salesperson,'level':request.session['level']})
